import store, { AppDispatch } from '@/store/index';
import { getSearchResult, getSuggestionAPI } from '@/api/search';
import { Article, SearchAction, searchQuery } from '../reducer/search';
import { setHistory } from '@/utils/storage';

export function getSuggestionActionCreator(q: string) {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggestionAPI(q);
    // console.log(8, res);
    dispatch({
      type: 'search/saveSuggestion',
      payload: res.data.options,
    });
  };
}

// 清空redux的搜索建议
export function clearSuggestionActionCreator(): SearchAction {
  return {
    type: 'search/clearSuggestion',
  };
}

// 添加搜索历史
export function addHistoryActionCreator(keyWord: string) {
  return {
    // // 获取原来的历史记录
    // const { histories } = store.getState().search;
    // // 添加历史记录,并进行数组去重
    // const newHistory = Array.from(new Set([keyWord, ...histories]));
    // // 限制搜索历史数量
    // if (newHistory.length > 10) newHistory.length = 10;
    // 保存在redux中

    type: 'search/saveHistory',
    payload: keyWord,

    // setHistory(newHistory);
  };
}

// 清空全部搜索历史
export function clearHistoryActionCreator(): SearchAction {
  return {
    type: 'search/clearHistory',
  };
}

// 保存搜索结果
export function getResultActionCreator(payload: searchQuery) {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResult(payload);
    // console.log(54, res);
    dispatch({
      type: 'search/saveResults',
      payload: res.data.results,
    });
  };
}

// 清空搜索结果
export function clearResultActionCreator(): SearchAction {
  return {
    type: 'search/clearResults',
  };
}
